<!--
 * @Date: 2020-08-13 09:28:27
 * @LastEditors: leehave
 * @LastEditTime: 2020-08-26 16:08:27
-->
<template>
  <div class="bind-phone">
    <van-form @submit="submitPhone">
      <van-cell title="国家/地区" is-link />
      <van-field
        v-model="phone"
        type="tel"
        name="phone"
        label="手机号"
        placeholder="手机号"
        trigger="onChange"
        :rules="[{ required: true, message: msgFun, validator:handleValidate }]"
      >
      <template #button>
        <van-button size="small" type="primary">获取验证码</van-button>
      </template>
      </van-field>
      <van-field
        v-model="phoneCompare"
        type="tel"
        name="comparePhone"
        label="短信验证码"
        placeholder="请填写短信验证码"
        trigger="onChange"
        @blur="handleComparePhone"
        :rules="[{ required: true, message: msgFun, validator:handleValidate }]"
      />
      <div style="padding: 20px 80px">
        <van-button round block type="info" native-type="submit">确定</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import {isPhoneNum} from '@/utils/validate.js';
import { updatePhone } from '@/service/user';
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      username: this.$store.state.user.userInfo.userName,
      phone: this.$store.state.user.userInfo.phone,
      phoneCompare: this.$store.state.user.userInfo.phone
    };
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created() {},
  mounted() {},
  watch: {},
  methods: {
    handleValidate(value,rule){
      if(!isPhoneNum(value)){
        return false
      }
    },
    msgFun(value,rule){
      if(value == ''){
        return '请填写手机号'
      } else if(!isPhoneNum(value)){
        return '手机号格式错误'
      }
    },
    handleComparePhone(){
      if(this.phone == ''){
        this.$toast('请输入手机号')
        return
      }
      if(this.phone !== this.phoneCompare){
        this.$toast('请确保两次输入手机号相同')
        return
      }
    },
    async submitPhone(values){
      
      if(this.phone == ''){
        this.$toast('请填写手机号')
        return
      }
      if(this.phone !== this.phoneCompare){
        this.$toast('请确保两次输入手机号相同')
        return
      }
      let params = {
        openId: this.userInfo.openId,
        username: this.username,
        phone: this.phone
      }
      updatePhone(params).then(res => {
        if(res.status == '200'){
          this.$store.dispatch('user/updateUserInfo',this.userInfo.openId)
          this.$router.replace({
            path: '/home'
          })
        }else{
          this.$store.dispatch('user/updateUserInfo',this.userInfo.openId)
          this.$router.replace({
            path: '/home'
          })
        }
      })

      console.log(values)
    }
  },
  components: {},
};
</script>

<style lang="less">
</style>
